package com.demo.deadLock;

/**
 * 账户
 */
public class Account {

	private final Allocator actr = Allocator.getInstance();
	private int balance;

	/**
	 * 转账
	 *
	 * @param target 目标账户
	 * @param amt    转账金额
	 */
	void transfer(Account target, int amt) {
		while (!actr.apply(this, target)) {

		}
		try {
			synchronized (this) {
				System.out.println(this + " lock obj1");
				synchronized (target) {
					System.out.println(this + " lock obj2");
					if (this.balance > amt) {
						this.balance -= amt;
						target.balance += amt;
					}
				}
			}
		} finally {
			//执行完后，再释放持有的资源
			actr.clean(this, target);
		}
	}
}
